import cv2
import numpy as np
import time
from PIL import Image
from file import *
from PyCameraList.camera_device import list_video_devices
import os
from lb_log import *
#import logging
#logging.basicConfig(format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s',
#                    level=logging.DEBUG)

# lb_logger = logging.getLogger('light_box')
# lb_logger.setLevel(logging.DEBUG)
# lb_formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')

# lb_file_handler = logging.FileHandler('light_box_test.log', encoding="utf-8", mode="a")
# lb_file_handler.setLevel(level=logging.INFO)
# lb_file_handler.setFormatter(lb_formatter)

# lb_stream_handler = logging.StreamHandler()
# lb_stream_handler.setLevel(logging.DEBUG)
# lb_stream_handler.setFormatter(lb_formatter)

# lb_logger.addHandler(lb_file_handler)
# lb_logger.addHandler(lb_stream_handler)



# offsetW_S = (-120, 100, -120, 100)
# offsetW_E = (-100, 120, -100, 120)
# offsetH_S = (-120, -120, 100, 100)
# offsetH_E = (-100, -100, 120, 120)

offsetW_S = (-600, 500, -600, 500)
offsetW_E = (-500, 600, -500, 600)
offsetH_S = (-500, -500, 400, 400)
offsetH_E = (-400, -400, 500, 500)


imageName = 'image'
imageCopyName = imageName + 'Copy'

class CameraCap(object):
    """ 打开视频流 """
    def __init__(self):
        camerasID = 500
        cameras = list_video_devices()
        print(dict(cameras))
        for d in dict(cameras):
            print(cameras[d][1])
            if 'Video Device' in cameras[d][1]:
                camerasID = d
        print('XW500 id=', camerasID)
        lb_logger.info('camerasID=%s', camerasID)
        if camerasID != 500:
            self.cap = cv2.VideoCapture(camerasID + cv2.CAP_DSHOW)
            # self.cap.set(cv2.CAP_PROP_FPS, 120) 
            self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 2592)
            self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1944)
            self.cap.set(cv2.CAP_PROP_AUTO_WB, 0)
            self.cap.set(cv2.CAP_PROP_WB_TEMPERATURE, 5500)
            self.cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))
            print("camera init over")
            lb_logger.info("camera init over!")
        else:
            print("camera init failed cause no camera found")
            lb_logger.info("camera init failed cause no camera found")


    """ 逐帧读取数据并保存图片到本地制定位置 """
    def Camera_image(self, index):
        ret,frame = self.cap.read() #ret：True或者False，代表有没有读取到图片;frame：表示截取到一帧的图片
        if ret == False:
            return
                        
        # cv2.imshow('capture', frame) # 展示图片  
        # cv2.imwrite("./image" + str(index) +".jpg", frame)  # 保存图片
        if not os.path.exists(imagePath):
            os.mkdir(imagePath)
        imgPath = imagePath + imageName + str(index) +".jpg"               
        cv2.imwrite(imgPath, frame)  # 保存图片
        return imgPath

    def camera_close(self):
        self.cap.release() # 释放对象和销毁窗口
        cv2.destroyAllWindows()

def mean_rgb(path, left, upper, right, lower):
    """
        所截区域图片保存
    :param path:图片路径
    :param left:区块左上角位置的像素点离图片左边界的距离
    :param upper:区块左上角位置的像素点离图片上边界的距离
    :param right:区块右下角位置的像素点离图片左边界的距离
    :param lower:区块右下角位置的像素点离图片上边界的距离
     故需满足:lower > upper、right > left
    """
    img = Image.open(path)  # 打开图像
    box = (left, upper, right, lower) #需要裁剪的图片区域
    roi = img.crop(box)
    rgb_im = roi.convert('RGB')

    # #展示裁剪后的图片区域
    # plt.imshow(roi)
    # plt.axis('off')
    # plt.show()
    
    #计算裁剪后的图片区域的平均rgb值
    s1=[]
    s2=[]
    s3=[]
    (w,h)=rgb_im.size

    for i in range(w):  #
        for j in range(h):
            r, g, b = rgb_im.getpixel((i, j)) #读取每一点的RGB值
            #黑色rgb（0，0，0），s1\s2\s3中均不包含黑色区域的rgb值
            if r>0:
                s1.append(r)
            if g>0:
                s2.append(g)
            if b>0:
                s3.append(b)
    #计算平均r值
    if len(s1)==0 :
        r_mean=0
    else:
        r_mean=np.mean(s1)
    #计算平均g值
    if len(s2)==0:
        g_mean=0
    else:
        g_mean=np.mean(s2)
    #计算平均b值
    if len(s3)==0:
        b_mean=0
    else:
        b_mean=np.mean(s3)

    r_mean = int(r_mean)
    g_mean = int(g_mean)
    b_mean = int(b_mean)
    print(path,"RGB: ", r_mean, g_mean, b_mean) #输出rgb平均值   
    lb_logger.info("RGB: %d  %d %d", r_mean, g_mean, b_mean)
    return r_mean, g_mean, b_mean

def processingRawImage(ima):
    img = cv2.imread(ima)
    sp = img.shape
    print(sp)

    w = int(sp[0] / 2)
    h = int(sp[1] / 2)

    imgList = ["img0","img1","img2","img3"]

    i = int(0)
    for i in range(0, 4):
        cropped = img[w+offsetW_S[i]:w+offsetW_E[i],h+offsetH_S[i]:h+offsetH_E[i]]
        imgList[i] = imagePath + imageCopyName + str(i) + ".jpg"
        cv2.imwrite(imgList[i],cropped)
    
    return imgList

def checkImageRGB(imaPath):
    imgCopyList = processingRawImage(imaPath)
    # print("copy=",imgCopyList)
    for v in imgCopyList:
        # print(v)
        mean_rgb(v, 0, 0, 100, 100)

# checkImageRGB('./test1.png')
if __name__ == "__main__":

    outmasages = CameraCap() 

    time.sleep(10)

    for i in range (0,4):
        image = outmasages.Camera_image(i) # 调用摄像头
        print(image)
        checkImageRGB(image)
        # checkImageRGB('./image/image'+str(i)+'.jpg')
        time.sleep(10)

    outmasages.camaro_close()



# outmasages.cap.release() # 释放对象和销毁窗口
# cv2.destroyAllWindows()

